//
//  StylesViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 9/2/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit

class StylesViewController: UITableViewController {
    
    var styles: [String: String]!
    var names: [String]!
    
    let userDefaults = NSUserDefaults.standardUserDefaults()
    let key = "style"
    
    var style: String!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let path = NSBundle.mainBundle().pathForResource("styles", ofType: "plist") {
            styles = NSDictionary(contentsOfFile: path) as! Dictionary<String, String>
            names = styles.keys.sort()
        }
        
        if userDefaults.objectForKey(key) != nil {
            style = userDefaults.objectForKey(key) as! String
        } else {
            userDefaults.setObject("default", forKey: key)
            userDefaults.synchronize()
            style = "default"
        }
    }

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return styles.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("style", forIndexPath: indexPath) 

        cell.textLabel?.text = names[indexPath.row]
        if style == styles[names[indexPath.row]] {
            cell.accessoryType = .Checkmark
        } else {
            cell.accessoryType = .None
        }

        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        let name = names[indexPath.row]
        style = styles[name]
        
        userDefaults.setObject(style, forKey: key)
        userDefaults.synchronize()
        
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.tableView.reloadData()
        })
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
